import os
import sys
# DON'T CHANGE THIS !!!
sys.path.insert(0, os.path.dirname(os.path.dirname(__file__)))

from flask import Flask, send_from_directory
from flask_cors import CORS
from src.models.models import db, SystemConfig
from src.routes.subscriptions import subscriptions_bp
from src.routes.system import system_bp
from src.routes.downloads import downloads_bp
from src.services.scheduler import init_scheduler  # 导入 init_scheduler
from src.services.queue_processor import init_queue_processor  # 导入队列处理器初始化
from src.models.license import SoftwareLicense
from src.services.serial_generator import SerialGenerator
from src.services.network_info import NetworkInfoService
from src.services.xunlei_nas_token_refresher import XunleiNASTokenRefresher

app = Flask(__name__, static_folder=os.path.join(os.path.dirname(__file__), 'static'))
app.config['SECRET_KEY'] = 'asdf#FGSgvasgf$5$WGT'

# 启用CORS支持
CORS(app, origins="*")

PORT = 80

# 注册蓝图
app.register_blueprint(subscriptions_bp, url_prefix='/api')
app.register_blueprint(system_bp, url_prefix='/api')
app.register_blueprint(downloads_bp, url_prefix='/api')

# 数据库配置
app.config['SQLALCHEMY_DATABASE_URI'] = f"sqlite:///{os.path.join(os.path.dirname(__file__), 'database', 'app.db')}"
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db.init_app(app)

# 初始化数据库和配置
with app.app_context():
    db.create_all()

    # 初始化系统配置
    try:
        # 检查是否已有配置，如果没有则创建默认配置
        if not SystemConfig.query.filter_by(key='scheduler_enabled').first():
            SystemConfig.set_config('scheduler_enabled', 'false', '全局定时任务开关')

        if not SystemConfig.query.filter_by(key='crawl_interval').first():
            SystemConfig.set_config('crawl_interval', '60', '爬取时间间隔（分钟）')

        if not SystemConfig.query.filter_by(key='global_auto_download').first():
            SystemConfig.set_config('global_auto_download', 'false', '全局自动下载开关')

        if not SystemConfig.query.filter_by(key='xunlei_nas_host').first():
            SystemConfig.set_config('xunlei_nas_host', '', '远程迅雷API主机地址')

        if not SystemConfig.query.filter_by(key='xunlei_nas_credential').first():
            SystemConfig.set_config('xunlei_nas_credential', '',
                                    '远程迅雷API认证Token！')

        if not SystemConfig.query.filter_by(key='xunlei_nas_initial_dir_id').first():
            SystemConfig.set_config('xunlei_nas_initial_dir_id', '',
                                    '远程API初始父目录ID')

        if not SystemConfig.query.filter_by(key='xunlei_nas_device_space_id').first():
            SystemConfig.set_config('xunlei_nas_device_space_id', '',
                                    '远程API设备空间ID')

        if not SystemConfig.query.filter_by(key='xunlei_nas_last_updated').first():
            SystemConfig.set_config('xunlei_nas_last_updated', '',
                                    '迅雷NAS配置最后更新时间')

        # 获取并存储网络信息（每次部署强制更新）
        print("正在获取网络信息...")
        network_info = NetworkInfoService.get_all_network_info()
        
        # 强制更新网络信息配置
        SystemConfig.set_config('local_ip', network_info['local_ip'], '本地IP地址')
        SystemConfig.set_config('public_ip', network_info['public_ip'], '公网IP地址')
        SystemConfig.set_config('network_status', network_info['network_status'], '网络状态')
        SystemConfig.set_config('port', str(PORT), '系统端口号')
        
        print(f"网络信息已更新: 本地IP={network_info['local_ip']}, 公网IP={network_info['public_ip']}, 网络状态={network_info['network_status']}, 端口={PORT}")

        print("系统配置初始化完成")

        # 检查授权表是否有序列号，无则生成
        license_obj = SoftwareLicense.get_license()
        if not license_obj:
            generator = SerialGenerator()
            serial = generator.generate_serial()
            SoftwareLicense.create_license(serial, remark='系统首次启动自动生成')
            print(f"已生成软件序列号: {serial}")
        else:
            print(f"已存在授权序列号: {license_obj.serial}")

        # 初始化定时任务，并传入 app 实例
        init_scheduler(app)
        # 初始化队列处理器，并传入 app 实例
        init_queue_processor(app)

        # 启动迅雷NAS Token定时刷新器
        global xunlei_token_refresher
        xunlei_token_refresher = XunleiNASTokenRefresher(app)
        xunlei_token_refresher.start()

    except Exception as e:
        print(f"初始化配置失败: {str(e)}")


@app.route('/', defaults={'path': ''})
@app.route('/<path:path>')
def serve(path):
    static_folder_path = app.static_folder
    if static_folder_path is None:
        return "Static folder not configured", 404

    if path != "" and os.path.exists(os.path.join(static_folder_path, path)):
        return send_from_directory(static_folder_path, path)
    else:
        index_path = os.path.join(static_folder_path, 'index.html')
        if os.path.exists(index_path):
            return send_from_directory(static_folder_path, 'index.html')
        else:
            return "index.html not found", 404


if __name__ == '__main__':
    app.run(host='0.0.0.0', port=PORT, debug=False)

